#version 150

in  vec2 texCoord;
out vec4 fColor;

uniform sampler2D texture;
const float R = 1.8;

void main() 
{ 
    ivec2 ires = textureSize(texture,0);
	float Res = float(ires.s);

	vec2 st = texCoord;
	float Radius = Res * 0.5;
	vec2 xy = Res * st;

	vec2 dxy = xy - Res/2.;
	float r = length(dxy);
	float z = sqrt(Radius*Radius - r*r);

	vec2 beta;
	beta.x = (1.-1./R) * asin(dxy.x/sqrt(dxy.x * dxy.x + z*z));
	beta.y = (1.-1./R) * asin(dxy.y/sqrt(dxy.y * dxy.y + z*z));

	vec2 xy1 = xy;
	if(r <= Radius)
	{
		xy1.x = xy.x - z*tan(beta.x);
		xy1.y = xy.y - z*tan(beta.y);
	}
	st = xy1/Res; // restore coordinates

	vec3 irgb = texture2D( texture, st ).rgb;
	fColor = vec4( irgb, 1. );
}